local _G = GLOBAL

--================================================================================================================
--[[ 简单粗暴,给所有mod物品注册小木牌贴图,使得所有mod物品都能画在小木牌上,参考小班花的智能小木牌代码 ]]
--================================================================================================================
local mod_assets = {}
--读取所有已加载的mod
local enabledmods = ModManager.enabledmods

--hook一下加载prefabs 加载完prefabs在检索数据
local oldRegisterPrefabs = ModManager.RegisterPrefabs

ModManager.RegisterPrefabs = function(self)
    oldRegisterPrefabs(self)
    for i, modname in ipairs(enabledmods) do
        local mod = GLOBAL.ModManager:GetMod(modname)

        --检索 modmain里注册的资源
        if mod.Assets then
            local modatlas = {}
            local modatlas_build = {}
            --检索所有的贴图
            for k, v in ipairs(mod.Assets) do
                if v.type == "ATLAS" then
                    table.insert(modatlas, v.file)
                elseif v.type == "ATLAS_BUILD" then
                    table.insert(modatlas_build, v.file)
                end
            end
            --判断是否有对应的ATLAS_BUILD
            for k, v in ipairs(modatlas) do
                local notfind = true
                for x, y in ipairs(modatlas_build) do
                    if v == y then
                        notfind = false
                        break
                    end
                end
                if notfind then
                    --没有就插入
                    --因为注册的时候会自动搜索路径，所以自己注册的时候要还原回原来的路径
                    v = string.gsub(v, "%.%./mods/[^/]+/", "", 1)
                    table.insert(mod_assets, Asset("ATLAS_BUILD", v, 256))
                end
            end
        end

        --检索 prefabs 里注册的资源
        if mod.Prefabs then
            for n, prefab in pairs(mod.Prefabs) do
                local modatlas = {}
                local modatlas_build = {}
                --检索所有的贴图
                if prefab.assets then
                    for k, v in pairs(prefab.assets) do
                        if v.type == "ATLAS" then
                            table.insert(modatlas, v.file)
                        elseif v.type == "ATLAS_BUILD" then
                            table.insert(modatlas_build, v.file)
                        end
                    end
                end
                --判断是否有对应的ATLAS_BUILD
                for k, v in ipairs(modatlas) do
                    local notfind = true
                    for x, y in ipairs(modatlas_build) do
                        if v == y then
                            notfind = false
                            break
                        end
                    end
                    if notfind then
                        --没有就插入
                        v = string.gsub(v, "%.%./mods/[^/]+/", "", 1)
                        table.insert(mod_assets, Asset("ATLAS_BUILD", v, 256))
                    end
                end
            end
        end
    end
    RegisterPrefabs(Prefab("MOD_assets", nil, mod_assets, nil, true))
    TheSim:LoadPrefabs({ "MOD_assets" })
    table.insert(self.loadedprefabs, "MOD_assets")
end

local function drawn(inst)
    if inst.components.drawable then
        local ondrawnfn = inst.components.drawable.ondrawnfn
        inst.components.drawable:SetOnDrawnFn(function(_, image, src, atlas, bgimage, bgatlas)
            if atlas then
                atlas = resolvefilepath_soft(atlas)
            end
            if ondrawnfn then
                ondrawnfn(inst, image, src, atlas, bgimage, bgatlas)
            end
        end)
    end
end
AddPrefabPostInit("minisign", drawn)
AddPrefabPostInit("minisign_drawn", drawn)
AddPrefabPostInit("decor_pictureframe", drawn)

--================================================================================================================
--[[ 重写小木牌的绘图机制，让小木牌可以画上本mod里的256*256高清贴图 ]]
--================================================================================================================
local invPrefabList = require("tf_minisign_list")                               --mod中有物品栏图片的prefabs的表
local invBuildMaps = { "tf_minisign1", "tf_minisign2", "tf_minisign3" }
local function OnDrawn_minisign(inst, image, src, atlas, bgimage, bgatlas, ...) --这里image是所用图片的名字，而非prefab的名字
    if inst.drawable_ondrawnfn_t ~= nil then
        inst.drawable_ondrawnfn_t(inst, image, src, atlas, bgimage, bgatlas, ...)
    end
    --src在重载后就没了，所以没法让信息存在src里
    if image ~= nil and invPrefabList[image] ~= nil then
        inst.AnimState:OverrideSymbol("SWAP_SIGN", invBuildMaps[invPrefabList[image]] or invBuildMaps[1], image)
    end
    if bgimage ~= nil and invPrefabList[bgimage] ~= nil then
        inst.AnimState:OverrideSymbol("SWAP_SIGN_BG", invBuildMaps[invPrefabList[bgimage]] or invBuildMaps[1], bgimage)
    end
end
local function MiniSign_init(inst)
    if inst.drawable_ondrawnfn_t == nil and inst.components.drawable ~= nil then
        inst.drawable_ondrawnfn_t = inst.components.drawable.ondrawnfn
        inst.components.drawable:SetOnDrawnFn(OnDrawn_minisign)
    end
end
AddPrefabPostInit("minisign", MiniSign_init)
AddPrefabPostInit("minisign_drawn", MiniSign_init)
AddPrefabPostInit("decor_pictureframe", MiniSign_init)

--================================================================================================================
--[[ 高清256*256贴图兼容棱镜的白木展示柜 ]]
--================================================================================================================
local function Tf_SetShowSlot(inst, slot)
    local item = inst.components.container.slots[slot]
    if item ~= nil then
        local bgimage
        local image = FunctionOrValue(item.drawimageoverride, item, inst) or (#(item.components.inventoryitem.imagename or "") > 0 and item.components.inventoryitem.imagename) or item.prefab or nil
        if image ~= nil then
            if item.inv_image_bg ~= nil and item.inv_image_bg.image ~= nil and item.inv_image_bg.image:len() > 4 and item.inv_image_bg.image:sub(-4):lower() == ".tex" then
                bgimage = item.inv_image_bg.image:sub(1, -5)
            end
            if invPrefabList[image] ~= nil then
                inst.AnimState:ClearOverrideSymbol("slot" .. tostring(slot))
                inst.AnimState:OverrideSymbol("slot" .. tostring(slot), invBuildMaps[invPrefabList[image]] or invBuildMaps[1], image)
            end
            if bgimage ~= nil then
                if invPrefabList[bgimage] ~= nil then
                    inst.AnimState:ClearOverrideSymbol("slotbg" .. tostring(slot))
                    inst.AnimState:OverrideSymbol("slotbg" .. tostring(slot), invBuildMaps[invPrefabList[bgimage]] or invBuildMaps[1], bgimage)
                end
            end
        end
    end
end
local function Tf_ItemGet_chest(inst, data)
    if data and data.slot and data.slot <= inst.shownum_l then
        Tf_SetShowSlot(inst, data.slot)
    end
end
local function HookWhitewood(inst)
    if not TheWorld.ismastersim then
        return
    end
    local old_onclosefn = inst.components.container.onclosefn
    local function OnClose_chest(inst)
        old_onclosefn(inst)
        if not inst:HasTag("burnt") then
            for i = 1, inst.shownum_l, 1 do
                Tf_SetShowSlot(inst, i)
            end
        end
    end
    inst.components.container.onclosefn = OnClose_chest
    inst:ListenForEvent("itemget", Tf_ItemGet_chest)
end
if _G.TF_SETS.ENABLEDMODS["legion"] then
    AddPrefabPostInit("chest_whitewood", HookWhitewood)
    AddPrefabPostInit("chest_whitewood_inf", HookWhitewood)
    AddPrefabPostInit("chest_whitewood_big", HookWhitewood)
    AddPrefabPostInit("chest_whitewood_big_inf", HookWhitewood)
end

if _G.TF_SETS.ENABLEDMODS["legion"] then
    --冰柜兼容棱镜的高清贴图:若是棱镜更新了,检查一下这个表有无增减
    local invPrefabList_legion = require("tf_minisign_list_legion")
    local invBuildMaps_legion = {
        "images_minisign1", "images_minisign2", "images_minisign3",
        "images_minisign4", "images_minisign5", "images_minisign6",
        "images_minisign_skins1", "images_minisign_skins2" --7、8
    }
    local function Tf_For_Legion_SetShowSlot(inst, slot)
        local item = inst.components.container.slots[slot]
        if item ~= nil then
            local bgimage
            local image = FunctionOrValue(item.drawimageoverride, item, inst) or (#(item.components.inventoryitem.imagename or "") > 0 and item.components.inventoryitem.imagename) or item.prefab or nil
            if image ~= nil then
                if item.inv_image_bg ~= nil and item.inv_image_bg.image ~= nil and item.inv_image_bg.image:len() > 4 and item.inv_image_bg.image:sub(-4):lower() == ".tex" then
                    bgimage = item.inv_image_bg.image:sub(1, -5)
                end
                if invPrefabList_legion[image] ~= nil then
                    inst.AnimState:ClearOverrideSymbol("slot" .. tostring(slot))
                    inst.AnimState:OverrideSymbol("slot" .. tostring(slot), invBuildMaps_legion[invPrefabList_legion[image]] or invBuildMaps_legion[1], image)
                end
                if bgimage ~= nil then
                    if invPrefabList_legion[bgimage] ~= nil then
                        inst.AnimState:ClearOverrideSymbol("slotbg" .. tostring(slot))
                        inst.AnimState:OverrideSymbol("slotbg" .. tostring(slot), invBuildMaps_legion[invPrefabList_legion[bgimage]] or invBuildMaps_legion[1], bgimage)
                    end
                end
            end
        end
    end
    local function Tf_For_Legion_ItemGet_chest(inst, data)
        if data and data.slot and data.slot <= 9 then
            Tf_For_Legion_SetShowSlot(inst, data.slot)
        end
    end
    local function HookBeverageCabinet(inst)
        if not TheWorld.ismastersim then
            return
        end
        local old_onclosefn = inst.components.container.onclosefn
        local function OnClose_chest(inst)
            old_onclosefn(inst)
            for i = 1, 9, 1 do
                Tf_For_Legion_SetShowSlot(inst, i)
            end
        end
        inst.components.container.onclosefn = OnClose_chest
        inst:ListenForEvent("itemget", Tf_For_Legion_ItemGet_chest)
    end
    AddPrefabPostInit("tf_beverage_cabinet", HookBeverageCabinet)
end
